package io.github.talelin.latticy.execl.oms.Product;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import io.github.talelin.autoconfigure.exception.ForbiddenException;
import io.github.talelin.latticy.common.LocalUser;
import io.github.talelin.latticy.common.util.BeanUtils;
import io.github.talelin.latticy.dto.oms.product.ProductDTO;
import io.github.talelin.latticy.model.oms.ProductBarcodeDO;
import io.github.talelin.latticy.model.oms.ProductShopDO;
import io.github.talelin.latticy.service.oms.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @ClassName：ProductDataListener
 * @Author: ljj
 * @Date: 2022/5/11 9:24
 */
@Slf4j
public class ProductDataListener implements ReadListener<ProductExecl> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;

    private List<ProductExecl> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private ProductService productService;

    public ProductDataListener(ProductService productService) {
        // 这里是demo，所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
        this.productService = productService;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     * @param analysisContext
     */
    @Override
    public void invoke(ProductExecl data, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        Optional.ofNullable(data).ifPresent(this::checkParam);
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        List<ProductDTO> productDTOS = new ArrayList<>();
        for (ProductExecl productExecl : cachedDataList) {
            ProductDTO productDTO = BeanUtils.copyProperties(productExecl, ProductDTO.class);
            productDTO.setTenant(LocalUser.getLocalUser().getTenant());
            getShops(productExecl, productDTO);
            getBarcodes(productExecl, productDTO);
            productDTO.setCreatorCode(LocalUser.getLocalUser().getUsername());
            productDTOS.add(productDTO);
        }
        productService.batchSave(productDTOS);
        log.info("存储数据库成功！");
    }


    private void getBarcodes(ProductExecl productExecl, ProductDTO productDTO) {
        if (StringUtils.isNotEmpty(productExecl.getBarcode())) {
            String[] split = productExecl.getBarcode().split(",");
            if (split.length > 0) {
                List<ProductBarcodeDO> barcode = new ArrayList<>();
                for (String s : split) {
                    String[] split1 = s.split("#");
                    if (split1.length == 2) {
                        ProductBarcodeDO productBarcodeDO = new ProductBarcodeDO();
                        productBarcodeDO.setCustomCodeName(split1[0]);
                        productBarcodeDO.setCustomCode(split1[1]);
                        barcode.add(productBarcodeDO);
                    }
                }
                productDTO.setProductBarcodes(barcode);
            }
        }
    }

    private void getShops(ProductExecl productExecl, ProductDTO productDTO) {
        if (StringUtils.isNotEmpty(productExecl.getShops())) {
            String[] split = productExecl.getShops().split(",");
            if (split.length > 0) {
                List<ProductShopDO> shops = new ArrayList<>();
                for (String s : split) {
                    String[] split1 = s.split("#");
                    if (split1.length == 2) {
                        ProductShopDO productShopDO = new ProductShopDO();
                        productShopDO.setShopCode(split1[0]);
                        productShopDO.setShopSku(split1[1]);
                        shops.add(productShopDO);
                    }
                }
                productDTO.setShops(shops);
            }
        }
    }

    /**
     * 判断数据
     *
     * @param productExecl
     */
    public void checkParam(ProductExecl productExecl) {
        if (StringUtils.isEmpty(productExecl.getSku())) {
            throw new ForbiddenException(15003);
        }
        if (productExecl.getLength() == null || productExecl.getWidth() == null
                || productExecl.getHeight() == null || productExecl.getWidth() == null
                || productExecl.getLwhType() == null || productExecl.getWeightType() == null) {
            throw new ForbiddenException(15004);
        }
        if (StringUtils.isEmpty(productExecl.getName())) {
            throw new ForbiddenException(15007);
        }
        if (productExecl.getCategoryId() == null) {
            throw new ForbiddenException(15008);
        }
        if (productExecl.getPackagType() == null) {
            throw new ForbiddenException(15009);
        }
    }
}
